# -*- coding: utf-8 -*-
"""
调试工具，用于测试RabbitMQ连接和消息发送
"""
import pika
import json
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def connect_rabbitmq():
    """建立RabbitMQ连接"""
    try:
        # 连接参数
        credentials = pika.PlainCredentials('root', 'root')
        parameters = pika.ConnectionParameters(
            host='localhost',
            port=5672,
            virtual_host='/',
            credentials=credentials,
            heartbeat=0,
            blocked_connection_timeout=300
        )
        
        # 建立连接
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        logger.info("Successfully connected to RabbitMQ")
        return connection, channel
    except Exception as e:
        logger.error(f"Failed to connect to RabbitMQ: {e}")
        raise

def send_test_message(channel, queue_name, message):
    """发送测试消息到指定队列"""
    try:
        # 声明队列
        # channel.queue_declare(queue=queue_name, durable=True)
        
        # 发送消息
        channel.basic_publish(
            exchange='',
            routing_key=queue_name,
            body=json.dumps(message),
            properties=pika.BasicProperties(
                delivery_mode=2,  # 持久化消息
            )
        )
        logger.info(f"Sent message to queue '{queue_name}': {message}")
    except Exception as e:
        logger.error(f"Failed to send message: {e}")
        raise

def main():
    """主函数"""
    try:
        # 连接RabbitMQ
        connection, channel = connect_rabbitmq()
        
        # 测试消息
        test_message = {
            'url': 'https://books.toscrape.com/',
            'callback': 'parse_item',
            'priority': 1
        }
        
        # 发送消息
        queue_name = 'book-list-spider:requests'
        send_test_message(channel, queue_name, test_message)
        
        # 关闭连接
        # connection.close()
        # logger.info("Connection closed")
    except Exception as e:
        logger.error(f"Error in main: {e}")

if __name__ == '__main__':
    main()